<template>
  <basic-drawer
    :visible="visible"
    title="添加站点"
    ok-text="完成配置"
    @cancel="handleCancel"
    @open="handleOpen"
    @close="handleClose"
    @ok="handleOk">
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      layout="vertical"
      scroll-to-first-error>
      <!-- 
        <a-form-item field="quantity" label="数量" asterisk-position="end">
          <a-radio-group v-model="form.quantity">
            <a-radio :value="1">单个</a-radio>
            <a-radio :value="2">多个</a-radio>
          </a-radio-group>
          </a-form-item> 
          v-if="form.quantity === 1"
          <a-form-item v-else field="multi_domain" hide-label>
            <section class="relative">
              <a-textarea
                v-model="form.multi_domain"
                placeholder="请输入域名"
                class="w-full h-60" />
              <span class="absolute right-2 bottom-26px text-#BFC2C7"
                >{{ domainList.length }} / 20</span
              >
              <div class="text-5 text-xs/5">
                格式说明: 站点，回源协议，回源配置，自定义回源HOST
                ；一行一个，未填写端口时http端口默认80，https端口默认443
              </div>
            </section>
          </a-form-item>
          -->
      <a-form-item
        field="domain"
        label="域名"
        hide-asterisk
        asterisk-position="end">
        <a-input
          v-model="form.domain"
          placeholder="请输入域名"
          class="!w-100" />
      </a-form-item>
      <a-form-item
        field="region_id"
        label="选择区域"
        hide-asterisk
        asterisk-position="end">
        <a-select
          v-model="form.region_id"
          placeholder="请选择区域"
          class="!w-100">
          <a-option v-for="i in areaOptions" :key="i.value" :value="i.value">{{
            i.label
          }}</a-option>
        </a-select>
      </a-form-item>
      <a-form-item
        field="group_id"
        label="选择分组"
        hide-asterisk
        asterisk-position="end">
        <a-select
          v-model="form.group_id"
          placeholder="请选择分组"
          class="!w-100">
          <a-option v-for="i in groupOptions" :key="i.value" :value="i.value">{{
            i.label
          }}</a-option>
        </a-select>
      </a-form-item>
      <a-form-item
        field="origin_server.protocol"
        label="回源协议"
        hide-asterisk
        asterisk-position="end">
        <a-select
          v-model="form.origin_server.protocol"
          placeholder="请选择回源协议"
          class="!w-100">
          <a-option
            v-for="i in protocolOptions"
            :key="i.value"
            :value="i.value"
            :label="i.label" />
        </a-select>
      </a-form-item>
      <a-form-item
        field="origin_server.algorithm"
        label="回源类型"
        hide-asterisk
        asterisk-position="end"
        required>
        <a-radio-group v-model="form.origin_server.algorithm">
          <a-radio value="swrr">权重</a-radio>
          <a-radio value="round_robin">轮询</a-radio>
          <a-radio value="chash">哈希</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item
        required
        label="源站配置"
        hide-asterisk
        asterisk-position="end">
        <source-site-table
          ref="sourceTableRef"
          v-model:list="form.origin_server.origin_list"
          :algorithm="form.origin_server.algorithm" />
      </a-form-item>
      <a-form-item
        field="hostType"
        label="回源HOST"
        hide-asterisk
        asterisk-position="end"
        required
        :class="{ 'mb-0!': form.hostType }">
        <a-radio-group v-model="form.hostType">
          <a-radio :value="false">默认（域名本身）</a-radio>
          <a-radio :value="true">自定义</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item
        v-if="form.hostType"
        field="origin_server.origin_host"
        hide-label
        hide-asterisk
        asterisk-position="end"
        required>
        <a-input
          v-model="form.origin_server.origin_host"
          placeholder="请输入自定义域名"
          class="!w-100" />
      </a-form-item>
      <a-form-item field="remark" label="备注">
        <a-input
          v-model="form.remark"
          show-word-limit
          :max-length="20"
          placeholder="请输入备注"
          class="!w-100" />
      </a-form-item>
    </a-form>
    <analysis-record-dialog
      v-model:visible="analysisVisible"
      :record="analysisData"
      @close="handleCloseAll" />
  </basic-drawer>
</template>

<script setup lang="ts">
import { v4 as uuidV4 } from 'uuid'
// import type { ISourceSite } from '@/components/SourceSiteTable/types'
import { addApiSiteApi } from '@/apis/modules/site/site'
import { omit } from 'lodash-es'
import AnalysisRecordDialog from './AnalysisRecordDialog.vue'
interface IProps {
  visible: boolean
  areaOptions?: LabelValue[]
  groupOptions?: LabelValue[]
}
withDefaults(defineProps<IProps>(), {
  visible: false,
  loading: false
})
interface IEmit {
  (event: 'update:visible', value: boolean): void
  (event: 'refresh'): void
}

const emit = defineEmits<IEmit>()
const {
  visible: analysisVisible,
  open: openAnalysisDialog,
  data: analysisData
} = usePopup()
const formRef = ref()
const form = reactive({
  // quantity: 1,
  domain: '',
  // multi_domain: '',
  region_id: undefined,
  group_id: '-1',
  hostType: false,
  remark: '',
  origin_server: {
    algorithm: 'swrr',
    origin_host: '',
    protocol: '',
    origin_list: [{ uuid: uuidV4(), priority: 1, host: '', port: null }]
  }
})

const rules = {
  // quantity: [{ required: true, message: '请选择数量' }],
  domain: [
    { required: true, message: '请输入域名' },
    {
      validator: validatePanDomain
    }
  ],
  // multi_domain: [
  //   { required: true, message: '请填写规则', trigger: 'blur' },
  //   {
  //     validator(_value, callback) {
  //       if (domainList.value.length > 20) {
  //         callback('超过最大限制条数')
  //       }
  //       callback(
  //         validateHandler(domainList.value, (data, i) => {
  //           const error = `第${i + 1}行格式错误`
  //           return regExpValidateHandler(data, regexpMap.domain, error)
  //         })
  //       )
  //     }
  //   }
  // ],
  region_id: [{ required: true, message: '请选择区域' }],
  'origin_server.protocol': [{ required: true, message: '请选择回源协议' }],
  'origin_server.origin_host': [
    { required: true, message: '请输入自定义域名' },
    {
      validator: validateDomain
    }
  ]
}
// const domainList = computed(() => {
//   return form.multi_domain.split('\n').filter((item) => item.length)
// })
const sourceTableRef = ref()
// 打开弹窗
const handleOpen = () => {}
// 弹窗关闭
const handleClose = () => emit('update:visible', false)
// 弹窗确认

const handleCloseAll = () => {
  formRef.value?.resetFields()
  form.origin_server.origin_list = [
    { uuid: uuidV4(), priority: 1, host: '', port: null }
  ]
  handleClose()
  emit('refresh')
}
const handleOk = async () => {
  const error = await formRef.value?.validate()
  const error1 = await sourceTableRef.value.validate()
  if (error || error1[0]) return false
  const data = { ...omit(form, 'hostType') }
  const res = await addApiSiteApi({ ...data })
  openAnalysisDialog(res)
  // ToastUtils.success('添加成功')
}
// 弹窗取消
const handleCancel = () => emit('update:visible', false)
</script>
<style lang="less" scoped></style>
